package com.cls.business.service.impl;

import com.cls.business.vo.EvaluationResultVO;
import com.cls.business.vo.ExpertReviewResultVO;
import com.cls.business.vo.SummaryDeclareTopic;
import com.cls.common.enums.DictEnum;
import com.cls.common.utils.FastDFSUtil;
import com.cls.common.utils.POIUtil;
import com.cls.common.utils.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import java.io.*;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ExportExcelService {

    public static Workbook exportIntentionForm(Map<String, List<SummaryDeclareTopic>> data,String year, String templateUrl) throws Exception {
        final int titleNameIndex = 0;
        final int topicNameIndex = 1;
        final int fieldNameIndex = 2;
        final int recordIndex = 3;
        int curIndex = 0;
        if(StringUtils.isEmpty(year)){
            year = "";
        }
        String sheetName = year + "期次" + DictEnum.TEMPLATE_INTENTION.getName();
        byte[] bytes = FastDFSUtil.fileDetail(templateUrl);
        HSSFWorkbook wb = new HSSFWorkbook();
        InputStream is = new ByteArrayInputStream(bytes);
        HSSFWorkbook templatesWb = new HSSFWorkbook(is);
        HSSFSheet srcSheet = templatesWb.getSheetAt(0);
        try {
            POIUtil.createSheetByTemplate(wb, srcSheet, sheetName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String titleName[] = {sheetName};
        POIUtil.copyRowAndSetData(wb.getSheet(sheetName), curIndex++, srcSheet, titleNameIndex, titleName);
        for(Map.Entry<String, List<SummaryDeclareTopic>> entry : data.entrySet()){
            String mapKey = entry.getKey();
            String topicName[] = new String[1];
            topicName[0] = mapKey;
            POIUtil.copyRowAndSetData(wb.getSheet(sheetName), curIndex++, srcSheet, topicNameIndex,topicName);
            POIUtil.mergerRegionInRow(wb.getSheet(sheetName), curIndex -1, -1,-1);
            POIUtil.copyRow(wb.getSheet(sheetName), curIndex++, srcSheet, fieldNameIndex);
            List<SummaryDeclareTopic> mapValue = entry.getValue();
            for(SummaryDeclareTopic one: mapValue){
                String[] testData = convertObjectToArray(one);
                POIUtil.copyRowAndSetData(wb.getSheet(sheetName), curIndex++, srcSheet, recordIndex,testData);
            }
        }
        return wb;
    }

    private enum IntentionForm {
        CODE("序号","code", 0),
        SUBJECT_TYPE("学科","subjectType", 1),
        NAME("申报课题名称","name", 2),
        LEADER_NAME("主持人","leaderName", 3),
        COMPANY("所在单位/职务职称","companyAndTitleType", 4),
        ACHIEVEMENT_FORM_TYPE("成果形式","achievementFormType", 5),
        ACHIEVEMENT_FORM_SIZE("成果字数","achievementFormSize", 6),
        MAIN_POINT("主要观点","mainPoint", 7),
        NOTE("备注","note", 8);

        IntentionForm(String name, String code, int index){
            this.name = name;
            this.code = code;
            this.index = index;
        }
        private final String name;
        private final String code;
        private final int index;
    }

    private static String[] convertObjectToArray(Object object){
        IntentionForm[] fields = IntentionForm.values();
        String[] arr = new String[fields.length];
        for(IntentionForm one:fields){
            try {
                Field field = object.getClass().getDeclaredField(one.code.toString());
                field.setAccessible(true);
                arr[one.index] = String.valueOf(field.get(object));
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return arr;
    }

    private static String[] convertObjectToArray1(Object object){
        EvaluationResult[] fields = EvaluationResult.values();
        String[] arr = new String[fields.length];
        for(EvaluationResult one:fields){
            try {
                Field field = object.getClass().getDeclaredField(one.code.toString());
                field.setAccessible(true);
                arr[one.index] = String.valueOf(field.get(object));
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return arr;
    }

    private enum EvaluationResult {
        CODE("立项编号","itemCode", 0),
        NAME("课题名称","name", 1),
        LEADER_NAME("主持人","leaderName", 2),
        COMPANY("所在单位/职务职称","company", 3);

        EvaluationResult(String name, String code, int index){
            this.name = name;
            this.code = code;
            this.index = index;
        }
        private final String name;
        private final String code;
        private final int index;
    }


    public static Workbook exportEvaluationResult(Map<String, List<EvaluationResultVO>> data, String period, String templateUrl) throws Exception {
        final int titleNameIndex = 0;
        final int topicNameIndex = 1;
        final int fieldNameIndex = 2;
        final int recordIndex = 3;

        int curIndex = 0;
        if(StringUtils.isEmpty(period)){
            period = "";
        }
        String sheetName = period + "期次" + DictEnum.TEMPLATE_CONCLUDE_RESULT.getName();
        HSSFWorkbook wb = new HSSFWorkbook();
        byte[] bytes = FastDFSUtil.fileDetail(templateUrl);
        InputStream is = new ByteArrayInputStream(bytes);
        HSSFWorkbook templatesWb = new HSSFWorkbook(is);
        HSSFSheet srcSheet = templatesWb.getSheetAt(0);
        try {
            POIUtil.createSheetByTemplate(wb, srcSheet, sheetName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String titleName[] = {sheetName};
        POIUtil.copyRowAndSetData(wb.getSheet(sheetName), curIndex++, srcSheet, titleNameIndex, titleName);
        for(Map.Entry<String, List<EvaluationResultVO>> entry : data.entrySet()){
            String mapKey = entry.getKey();
            String topicName[] = new String[1];
            topicName[0] = mapKey;
            POIUtil.copyRowAndSetData(wb.getSheet(sheetName), curIndex++, srcSheet, topicNameIndex,topicName);
            POIUtil.mergerRegionInRow(wb.getSheet(sheetName), curIndex -1, -1,-1);
            POIUtil.copyRow(wb.getSheet(sheetName), curIndex++, srcSheet, fieldNameIndex);

            List<EvaluationResultVO> mapValue = entry.getValue();
            for(EvaluationResultVO one: mapValue){
                String[] testData = convertObjectToArray1(one);
                POIUtil.copyRowAndSetData(wb.getSheet(sheetName), curIndex++, srcSheet, recordIndex,testData);
            }
        }
        return wb;
    }

    private static String[] convertExpertReviewResultToArray(ExpertReviewResultVO reviewResult){
        if(reviewResult == null){
            return null;
        }
        List<String> data = new ArrayList();
        data.add(reviewResult.getCode());
        data.add(reviewResult.getName());
        data.add(reviewResult.getLeaderName());
        data.add(reviewResult.getCompany());
        data.addAll(reviewResult.getScores());
        data.add(reviewResult.getTotalScore() + "");
        data.add(reviewResult.getOpinion() + "");
        return data.toArray(new String[data.size()]);
    }

    public static Workbook exportExpertReviewResult(Map<Long, Map<Long, ExpertReviewResultVO>> data, Map<Long, String> experts, String period,  String templateUrl) throws Exception {
        final int titleNameIndex = 0;
        final int expertNameIndex = 1;
        final int fieldNameIndex1 = 2;
        final int fieldNameIndex2 = 3;
        final int recordIndex = 4;
        int curIndex = 0;
        if(StringUtils.isEmpty(period)){
            period = "";
        }
        String sheetName = period + "期次" + DictEnum.TEMPLATE_EXPERT_REVIEW.getName();
        HSSFWorkbook wb = new HSSFWorkbook();
        byte[] bytes = FastDFSUtil.fileDetail(templateUrl);
        InputStream is = new ByteArrayInputStream(bytes);
        HSSFWorkbook templatesWb = new HSSFWorkbook(is);
        HSSFSheet srcSheet = templatesWb.getSheetAt(0);
        try {
            POIUtil.createSheetByTemplate(wb, srcSheet, sheetName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String titleName[] = {sheetName};
        POIUtil.copyRowAndSetData(wb.getSheet(sheetName), curIndex++, srcSheet, titleNameIndex, titleName);
        for(Map.Entry<Long, Map<Long, ExpertReviewResultVO>> entry : data.entrySet()) {
            Long mapKey = entry.getKey();
            String exportName[] = new String[]{""};
            if(experts.get(mapKey) != null){
                exportName[0] = experts.get(mapKey);
            }
            POIUtil.copyRowAndSetData(wb.getSheet(sheetName), curIndex++, srcSheet, expertNameIndex,exportName);
            POIUtil.mergerRegionInRow(wb.getSheet(sheetName), curIndex -1, -1,-1);
            POIUtil.copyRow(wb.getSheet(sheetName), curIndex++, srcSheet, fieldNameIndex1);
            POIUtil.mergerRegionInRow(wb.getSheet(sheetName), curIndex -1, 4,9);
            POIUtil.copyRow(wb.getSheet(sheetName), curIndex++, srcSheet, fieldNameIndex2);
            POIUtil.mergerRegion(wb.getSheet(sheetName), curIndex -2,curIndex -1, 0,0);
            POIUtil.mergerRegion(wb.getSheet(sheetName), curIndex -2,curIndex -1, 1,1);
            POIUtil.mergerRegion(wb.getSheet(sheetName), curIndex -2,curIndex -1, 2,2);
            POIUtil.mergerRegion(wb.getSheet(sheetName), curIndex -2,curIndex -1, 3,3);
            POIUtil.mergerRegion(wb.getSheet(sheetName), curIndex -2,curIndex -1, 10,10);
            POIUtil.mergerRegion(wb.getSheet(sheetName), curIndex -2,curIndex -1, 11,11);
            Map<Long, ExpertReviewResultVO> mapValue = entry.getValue();
            for(ExpertReviewResultVO one: mapValue.values()){
                String[] testData = convertExpertReviewResultToArray(one);
                POIUtil.copyRowAndSetData(wb.getSheet(sheetName), curIndex++, srcSheet, recordIndex,testData);
            }
        }
        return wb;
    }


    public static Workbook exportEntrustTopic(List<SummaryDeclareTopic> data, String period,  String templateUrl) throws Exception {
        final int titleNameIndex = 0;
        final int fieldNameIndex = 1;
        final int recordIndex =2;
        int curIndex = 0;
        if(StringUtils.isEmpty(period)){
            period = "";
        }
        String sheetName = period + "期次" + DictEnum.TEMPLATE_ENTRUST_TOPIC.getName();
        HSSFWorkbook wb = new HSSFWorkbook();
        byte[] bytes = FastDFSUtil.fileDetail(templateUrl);
        InputStream is = new ByteArrayInputStream(bytes);
        HSSFWorkbook templatesWb = new HSSFWorkbook(is);
        HSSFSheet srcSheet = templatesWb.getSheetAt(0);
        try {
            POIUtil.createSheetByTemplate(wb, srcSheet, sheetName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String titleName[] = {sheetName};
        POIUtil.copyRowAndSetData(wb.getSheet(sheetName), curIndex++, srcSheet, titleNameIndex, titleName);
        POIUtil.copyRow(wb.getSheet(sheetName), curIndex++, srcSheet, fieldNameIndex);
        for(SummaryDeclareTopic one:data) {
            String[] testData = convertEntrustTopicToArray(one);
            POIUtil.copyRowAndSetData(wb.getSheet(sheetName), curIndex++, srcSheet, recordIndex,testData);
        }
        return wb;
    }

    private static String[] convertEntrustTopicToArray(SummaryDeclareTopic entrust){
        if(entrust == null){
            return null;
        }
        List<String> data = new ArrayList();
        data.add(entrust.getItemCode());
        data.add(entrust.getName());
        data.add(entrust.getTopicCode());
        data.add(entrust.getLevelType());
        data.add(entrust.getTopicUnitName());
        data.add(entrust.getInitiator());
        data.add(entrust.getLeaderName());
        data.add(entrust.getCompanyAndTitleType());
        data.add(entrust.getMobile());
        data.add(entrust.getEmail());
        data.add(entrust.getMemberNames());
        return data.toArray(new String[data.size()]);
    }
}
